/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package cn.apestar.modules.meibang.meibanguserandclient.web;

import cn.apestar.common.config.Global;
import cn.apestar.common.image.FileUtilsIo;
import cn.apestar.common.persistence.Page;
import cn.apestar.common.utils.BeanUtil;
import cn.apestar.common.utils.CommonUtil;
import cn.apestar.common.utils.Encodes;
import cn.apestar.common.utils.excel.ImportExcel;
import cn.apestar.common.web.BaseController;
import cn.apestar.modules.meibang.meibanguserandclient.entity.MeibangUserAndClient;
import cn.apestar.modules.meibang.meibanguserandclient.service.MeibangUserAndClientService;
import cn.apestar.modules.sys.entity.ApestarUser;
import cn.apestar.modules.sys.entity.User;
import cn.apestar.modules.sys.entity.WtUser;
import cn.apestar.modules.sys.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务管理客Controller
 *
 * @author yudw
 * @version 2017-05-03
 */
@Controller @RequestMapping(value = "${adminPath}/meibanguserandclient/meibangUserAndClient")
public class MeibangUserAndClientController extends BaseController {

    @Autowired private MeibangUserAndClientService meibangUserAndClientService;

    @Autowired UserService userService;

    @ModelAttribute public MeibangUserAndClient get(@RequestParam(required = false) String id) {
        MeibangUserAndClient entity = null;
        if (StringUtils.isNotBlank(id)) {
            entity = meibangUserAndClientService.get(id);
        }
        if (entity == null) {
            entity = new MeibangUserAndClient();
        }
        return entity;
    }

    @RequestMapping(value = {"list", ""})
    public String list(MeibangUserAndClient meibangUserAndClient, HttpServletRequest request,
        HttpServletResponse response, Model model) {
        Page<MeibangUserAndClient> page = meibangUserAndClientService
            .findPage(new Page<MeibangUserAndClient>(request, response), meibangUserAndClient);
        model.addAttribute("page", page);
        return "modules/meibang/meibanguserandclient/meibangUserAndClientList";
    }

    @RequestMapping(value = "form")
    public String form(MeibangUserAndClient meibangUserAndClient, Model model) {
        model.addAttribute("meibangUserAndClient", meibangUserAndClient);
        return "modules/meibang/meibanguserandclient/meibangUserAndClientForm";
    }

    @RequestMapping(value = "save")
    public String save(MeibangUserAndClient meibangUserAndClient, Model model,
        RedirectAttributes redirectAttributes) {
        if (!beanValidator(model, meibangUserAndClient)) {
            return form(meibangUserAndClient, model);
        }
        meibangUserAndClientService.save(meibangUserAndClient);
        addMessage(redirectAttributes, "保存业务管理客成功");
        return "redirect:" + Global.getAdminPath()
            + "/meibanguserandclient/meibangUserAndClient/?repage";
    }

    @RequestMapping(value = "delete")
    public String delete(MeibangUserAndClient meibangUserAndClient,
        RedirectAttributes redirectAttributes) {
        meibangUserAndClientService.delete(meibangUserAndClient);
        addMessage(redirectAttributes, "删除业务管理客成功");
        return "redirect:" + Global.getAdminPath()
            + "/meibanguserandclient/meibangUserAndClient/?repage";
    }

    @RequestMapping(value = "import", method = RequestMethod.POST)
    public String importData(MultipartFile file, RedirectAttributes redirectAttributes) {
        try {
            StringBuilder failureMsg = new StringBuilder();
            ImportExcel ei = new ImportExcel(file, 0, 0);
            List<MeibangUserAndClient> list = ei.getDataList(MeibangUserAndClient.class);

            ApestarUser apestarUser = new ApestarUser();

            StringBuffer masterPhones =
                cn.apestar.util.CommonUtil.getLongString(list, "masterAccount");
            StringBuffer userPhones = cn.apestar.util.CommonUtil.getLongString(list, "userAccount");

            String ids = CommonUtil
                .getInSql("a.account", masterPhones.append(',').append(userPhones).toString());

            apestarUser.setIds(ids);
            List<WtUser> users = userService.getByIds(apestarUser);

            Map phoneForUsers = this.list2Map(users, "phone");

            for (MeibangUserAndClient user : list) {
                if (phoneForUsers.containsKey(user.getMasterAccount())) {
                    WtUser masterPhone = (WtUser) phoneForUsers.get(user.getMasterAccount());
                    User masterUser = new User();
                    masterUser.setId(masterPhone.getId());
                    user.setMaster(masterUser);
                    user.setCreateDate(new Date());
                }

                if (phoneForUsers.containsKey(user.getUserAccount())) {
                    WtUser userPhone = (WtUser) phoneForUsers.get(user.getUserAccount());
                    User userUser = new User();
                    userUser.setId(userPhone.getId());
                    user.setUser(userUser);
                    user.setCreateDate(new Date());
                }
            }

            meibangUserAndClientService.insertAll(list);

            addMessage(redirectAttributes, "已成功导入 " + list.size() + " 条用户" + failureMsg);
        } catch (Exception e) {
            addMessage(redirectAttributes, "导入用户失败！失败信息：" + e.getMessage());
        }
        return "redirect:" + Global.getAdminPath() + "/meibanguserandclient/meibangUserAndClient/";
    }

    private Map list2Map(List list, String key) {
        Map mapResult = new HashMap();
        for (int i = 0; i < list.size(); i++) {
            Object o = list.get(i);
            if (o == null)
                continue;
            Object property = BeanUtil.getProperty(o, key);
            mapResult.put(property, o);
        }
        return mapResult;
    }

    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletRequest request, HttpServletResponse response,
        RedirectAttributes redirectAttributes) {

        try {
            response.reset();

            String path = request.getSession().getServletContext().getRealPath("/");
            String typeName = request.getParameter("typeName");
            path = path + File.separator + "tpl" + File.separator + typeName + ".xls";
            String fileName = typeName + ".xls";
            fileName = encodeFileName(fileName, request);
            // 注意此时后缀.xls也要包含进去
            response.setContentType("application/vnd.ms-excel; charset=utf-8");
            response.setHeader("Content-Disposition",
                "attachment;filename=" + Encodes.urlEncode(fileName));
            FileUtilsIo.outputFile(path, response.getOutputStream());
        } catch (Exception e) {
            addMessage(redirectAttributes, "导入模板下载失败！失败信息：" + e.getMessage());
        }
        return "redirect:" + Global.getAdminPath() + "/taoxpkinfo/taoXpkInfo/?repage";
    }

    /**
     * 编译文件名
     *
     * @param filename 文件名
     * @param request  文件请求
     * @return
     */
    private String encodeFileName(String filename, HttpServletRequest request) {
        /**
         * 获取客户端浏览器和操作系统信息 在IE浏览器中得到的是：User-Agent=Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon; Alexa Toolbar)
         * 在Firefox中得到的是：User-Agent=Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.7.10) Gecko/20050717 Firefox/1.0.6
         */
        String agent = request.getHeader("USER-AGENT");
        try {
            if ((agent != null) && (-1 != agent.indexOf("MSIE"))) {
                String newFileName = URLEncoder.encode(filename, "UTF-8");
                newFileName = StringUtils.replace(newFileName, "+", "%20");
                if (newFileName.length() > 150) {
                    newFileName = new String(filename.getBytes("GB2312"), "ISO8859-1");
                    newFileName = StringUtils.replace(newFileName, " ", "%20");
                }
                return newFileName;
            }
            if ((agent != null) && (-1 != agent.indexOf("Mozilla"))) {
                return new String(filename.getBytes("UTF-8"), "ISO8859-1");
                // 下载javax.mail-api-1.4.7.jar包
                // return MimeUtility.encodeText(filename, "UTF-8", "B");
            }
            return filename;
        } catch (Exception ex) {
            return filename;
        }
    }
}